//
//  YJResultViewController.m
//  练习
//
//  Created by hcios on 2017/7/8.
//  Copyright © 2017年 hcios. All rights reserved.
//

#import "YJResultViewController.h"
#import "AFNetworking.h"
#import "YJResultModel.h"
#import "YJResultFrameModel.h"
#import "YJResultTableViewCell.h"
#import "YJResultHeaderView.h"
#import "YJResultAddTableViewCell.h"

#import "ZYShareItem.h"
#import "ZYShareView.h"

#import "UMSocialWechatHandler.h"
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "UIImageView+WebCache.h"
#import "XLPhotoBrowser.h"
#import "UIView+XLExtension.h"
#define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height
#define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width

@interface YJResultViewController ()<UITableViewDelegate,UITableViewDataSource,YJResultHeaderViewDelegate,YJResultTableViewCellDelagate,XLPhotoBrowserDelegate,XLPhotoBrowserDatasource>{
    
    UITableView *_tableView;
    UITableView *_addTableView;
    NSMutableArray *_dataSeationArr;
    NSMutableArray *_dataHeaderArr;
    NSMutableArray *_dataHeaderViewArr;
    NSMutableArray *_dataHeaderSectionArr;
    NSMutableArray *_dataEmptySectionArr;
    NSMutableArray *addTableViewSectionArr;
    
    NSIndexPath *_indexPath;
 
    UIButton *addButton;
    //返回顶部按钮
    UIButton *topButton;
    //顶部button
    UIButton *returnButton;
    
    UIButton *shareButton;
    
    YJResultHeaderView *header;
    
    NSMutableArray *_dataImageViewArray;
    
    NSMutableArray *_dataUrlArr;
    
    NSMutableArray *_dataUrlArraySection;
}

@end

@implementation YJResultViewController

-(instancetype)init{
    if (self = [super init]) {
        _dataSeationArr = [[NSMutableArray alloc] init];
        _dataHeaderArr = [[NSMutableArray alloc] init];
        _dataHeaderViewArr = [[NSMutableArray alloc] init];
        _dataHeaderSectionArr = [[NSMutableArray alloc] init];
        _dataEmptySectionArr = [[NSMutableArray alloc] init];
        _dataImageViewArray = [[NSMutableArray alloc] init];
        _dataUrlArraySection = [[NSMutableArray alloc] init];
        _dataUrlArr = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];

    [self initSubViews];
    [self netWorking];
    
    self.view.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBarHidden = YES;
}




#pragma mark - 初始化方法
-(void)initSubViews{
    _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _addTableView = [[UITableView alloc] initWithFrame:CGRectMake(-(SCREEN_WIDTH / 2), 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _addTableView.delegate = self;
    _addTableView.dataSource = self;
    _addTableView.showsVerticalScrollIndicator = NO;
    _addTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _addTableView.layer.borderWidth = 1;
    _addTableView.layer.backgroundColor = [UIColor blackColor].CGColor;
    
    
    //添加按钮
    addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [addButton setFrame:CGRectMake(10, SCREEN_HEIGHT - 100, 50, 50)];
    addButton.layer.cornerRadius = 25;
    addButton.layer.masksToBounds = YES;
    addButton.backgroundColor = [UIColor whiteColor];
    [addButton addTarget:self action:@selector(clickadd) forControlEvents:UIControlEventTouchUpInside];
    [addButton setImage:[UIImage imageNamed:@"resultAdd"] forState:UIControlStateNormal];
    [addButton.titleLabel setFont:[UIFont systemFontOfSize:11]];
    [self.view addSubview:addButton];
    [self.view bringSubviewToFront:addButton];
    
    
    //btnView
    topButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [topButton setFrame:CGRectMake(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 100, 50, 50)];
    topButton.layer.cornerRadius = 25;
    topButton.layer.masksToBounds = YES;
    [topButton setImage:[UIImage imageNamed:@"back_top"] forState:UIControlStateNormal];
    [topButton addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    [topButton.titleLabel setFont:[UIFont systemFontOfSize:11]];
    topButton.hidden = YES;
    [self.view addSubview:topButton];
    [self.view bringSubviewToFront:topButton];
    
    //returnButton
    returnButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [returnButton setFrame:CGRectMake(10, 20, 50, 50)];
    returnButton.layer.cornerRadius = 25;
    returnButton.layer.masksToBounds = YES;
    returnButton.alpha = 0.618;
    returnButton.backgroundColor = [UIColor blackColor];
    [returnButton setImage:[UIImage imageNamed:@"homepage_back_icon03"] forState:UIControlStateNormal];
    [returnButton addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:returnButton];
    [self.view bringSubviewToFront:returnButton];
    
    //shareButton
    shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setFrame:CGRectMake(SCREEN_WIDTH - 60, 20, 50, 50)];
    shareButton.layer.cornerRadius = 25;
    shareButton.layer.masksToBounds = YES;
    shareButton.alpha = 0.618;
    shareButton.backgroundColor = [UIColor blackColor];
    [shareButton setImage:[UIImage imageNamed:@"homepage_message_icon03"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
    [self.view bringSubviewToFront:shareButton];
}


#pragma mark - 点击事件
//返回上一页
-(void)returnBack{
    NSLog(@"点击");
    [[self navigationController]popViewControllerAnimated:YES];
}



//添加侧边栏
-(void)clickadd{
    NSLog(@"出现侧边栏");
    [self.view addSubview:_addTableView];
    [UIView animateWithDuration:0.7 animations:^{
        _addTableView.frame = CGRectMake(0, 0, (SCREEN_WIDTH / 2), SCREEN_HEIGHT);
    }];
}



//返回顶部
-(void)click{
    [_tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    topButton.hidden = YES;
}

//分享
- (void) share{
    
    __weak typeof(self) weakSelf = self;
    ZYShareItem *itemWeiXin = [ZYShareItem itemWithTitle:@"微信好友" icon:@"wechat-icon" handler:^{
        [weakSelf shareWebToWechat];
        NSLog(@"分享");
    }];
    
    NSArray *arr = @[itemWeiXin];
    ZYShareView *share = [ZYShareView shareViewWithShareItems:arr functionItems:nil];
    [share show];
}


#pragma mark - tableView数据源
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([tableView isEqual:_tableView]) {
        return [_dataSeationArr[section] count];
    }else{
        return  [_dataHeaderSectionArr[section] count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView isEqual:_tableView]) {
        YJResultTableViewCell *cell = [YJResultTableViewCell cellWithTableView:tableView];
        
        cell.frameModel = _dataSeationArr[indexPath.section][indexPath.row];
        cell.delegate = self;
        return cell;
    }else{
        NSString *cellID = [NSString stringWithFormat:@"cellID%ld%ld",(long)[indexPath section],(long)[indexPath row]];
        YJResultAddTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[YJResultAddTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            [cell layoutWithCellArray:_dataHeaderSectionArr[indexPath.section][indexPath.row]];
        }
        return cell;
    }
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if ([tableView isEqual:_tableView]) {
        
        return _dataSeationArr.count;
    }else{
        return _dataHeaderSectionArr.count;
    }
    
}




-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //判断点击哪个table
    if ([tableView isEqual:_tableView]) {
        [UIView animateWithDuration:0.7 animations:^{
            _addTableView.frame = CGRectMake(-(SCREEN_WIDTH / 2), 0, (SCREEN_WIDTH / 2), SCREEN_HEIGHT);
        }];
        [_addTableView removeFromSuperview];
    }
    
    if ([tableView isEqual:_addTableView]) {
        //计算出 右侧 tableView 将要滚动的位置
        NSInteger row = 0;
        for (int i = 0; i < indexPath.row; i++) {
            row = [_dataEmptySectionArr[indexPath.section][i] count] + row;
        }
        NSIndexPath *moveToIndexPathOne = [NSIndexPath indexPathForRow:row + 1 inSection:indexPath.section];
        NSIndexPath *moveToIndexPathTwo = [NSIndexPath indexPathForRow:row inSection:indexPath.section];
        //注意：这里要加上一个判断，这样才能跳到指定的位置
        //将右侧tableView移动到指定的位置
        if (indexPath.section == 0) {
            [_tableView selectRowAtIndexPath:moveToIndexPathOne animated:YES scrollPosition:UITableViewScrollPositionTop];
            //取消选中效果
            [_tableView deselectRowAtIndexPath:moveToIndexPathTwo animated:YES];
        }else{
            [_tableView selectRowAtIndexPath:moveToIndexPathTwo animated:YES scrollPosition:UITableViewScrollPositionTop];
            // 取消选中效果
            [_tableView deselectRowAtIndexPath:moveToIndexPathTwo animated:YES];
        }
        [_addTableView removeFromSuperview];
    }
}



#pragma mark - tableView代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView isEqual:_tableView]) {
        YJResultFrameModel *frameModel = _dataSeationArr[indexPath.section][indexPath.row];
        return frameModel.cellHeight;
    }else return 40;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if ([tableView isEqual:_tableView]) {
        if (section == 0) {
            return 300;
        }else return 20;
    }else return CGFLOAT_MIN;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
    
}


-(nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if ([tableView isEqual:_tableView]) {
        
        if (section == 0) {
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
            //头视图的背景图
            header = [[YJResultHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 280)];
            header.backImgView.contentMode = UIViewContentModeScaleAspectFill;
            header.model = _dataHeaderArr[0];
            //trip时间
            UILabel *headerLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 280, SCREEN_WIDTH, 20)];
            headerLab.text = _dataHeaderViewArr[section];
            headerLab.textAlignment = NSTextAlignmentCenter;
            [headerLab setFont:[UIFont systemFontOfSize:14]];
            [view addSubview:header];
            [view addSubview:headerLab];
            return view;
        }else{
            UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
            //trip时间
            UILabel *headerOtherLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
            headerOtherLab.text = _dataHeaderViewArr[section];
            headerOtherLab.textAlignment = NSTextAlignmentCenter;
            [headerOtherLab setFont:[UIFont systemFontOfSize:14]];
            [headerView addSubview:headerOtherLab];
            headerView.backgroundColor = [UIColor grayColor];
            return headerView;
        }
    }else{
        return nil;
    }
}





#pragma mark - netWorking
-(void)netWorking{
    
    NSString * urlString = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/%@.json",_selfID];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            //取出头视图信息
            YJResultModel *model = [[YJResultModel alloc] initWithHeaderDict:responseObject];
            [_dataHeaderArr addObject:model];
            
            //1.第一层遍历
            for (NSDictionary *trip_dict in responseObject[@"trip_days"]) {
                
                //取出头视图日期和天数
                NSString *timeString = [NSString stringWithFormat:@"DAY%@%@",trip_dict[@"day"],trip_dict[@"trip_date"]];
                [_dataHeaderViewArr addObject:timeString];
                
                //tableView的row的数组
                NSMutableArray *dataRowArr = [[NSMutableArray alloc] init];
                //addTabView的row的数组
                NSMutableArray *dataHeaderRowArr = [[NSMutableArray alloc] init];
                //空数组
                NSMutableArray *dataEmptyRowArr = [[NSMutableArray alloc] init];
                //图片url
                NSMutableArray *imageCountArr = [[NSMutableArray alloc] init];
                //图片
                NSMutableArray *imageViewCountArr = [[NSMutableArray alloc] init];
                //数组存储image
                NSMutableArray *imageArr = [[NSMutableArray alloc] init];
                
                
                //2.第二层遍历
                for (NSDictionary *nodes_dict in trip_dict[@"nodes"]) {
                    //取数据给addTableView
                    YJResultModel *addModel = [[YJResultModel alloc] initWithDict2:nodes_dict];
                    
                    //第三次遍历(取出空数组)
                    NSMutableArray *tripArray = [[NSMutableArray alloc] init];
                    for (NSDictionary *dictTow in nodes_dict[@"notes"]) {
                        YJResultModel *model4 = [[YJResultModel alloc] initWithDict3:dictTow];
                        YJResultFrameModel *frameModel4 = [[YJResultFrameModel alloc] init];
                        frameModel4.model = model4;
                        //次数组存储每个day里面的cell的个数
                        [tripArray addObject:frameModel4];
                    }
                    //判断是否为空
                    if (![addModel.nodes_entry_name isEqualToString:@""]) {
                        [dataEmptyRowArr addObject:tripArray];
                    }
                    //3.第三层遍历(取出添加标题)
                    [nodes_dict[@"notes"] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        NSMutableDictionary *mutDict = [[NSMutableDictionary alloc] initWithDictionary:obj];
                        if (idx == 0) {
                            //数据拼接
                            [mutDict setObject:nodes_dict[@"entry_name"] forKey:@"entry_name"];
                            [mutDict setObject:nodes_dict[@"comment"] forKey:@"comment"];
                        }
                        YJResultModel *model = [[YJResultModel alloc] initWithDict3:mutDict];
                        [_dataUrlArr addObject:model.photo_url];
                        UIImageView *imageView = [[UIImageView alloc] init];
                        [imageView sd_setImageWithURL:[NSURL URLWithString:model.photo_url]];
                        [imageArr addObject:imageView];
                        
                        YJResultFrameModel *frameModel = [[YJResultFrameModel alloc] init];
                        frameModel.model = model;
                        [dataRowArr addObject:frameModel];
                        
                        //拿到addTableView的row数组
                        if (![mutDict[@"entry_name"] isKindOfClass:[NSNull class]]) {
                            if(![model.nodes_entry_name isEqualToString:@""]){
                                [dataHeaderRowArr addObject:model.nodes_entry_name];
                            }
                        }
                    }];
                    imageCountArr = [NSMutableArray arrayWithArray:_dataUrlArr];
                    imageViewCountArr = [NSMutableArray arrayWithArray:imageArr];
                }
                //tableView的section的数组
                [_dataSeationArr addObject:dataRowArr];
                
                //addTableView的section的数组
                [_dataHeaderSectionArr addObject:dataHeaderRowArr];
                
                //占位section的数组
                [_dataEmptySectionArr addObject:dataEmptyRowArr];
                [_dataImageViewArray addObject:imageViewCountArr];
                [_dataUrlArraySection addObject:imageCountArr];
            }
        }
        [_tableView reloadData];
        [_addTableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"failure");
    }];
}





//上滑隐藏，下滑显示
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    if ([scrollView isEqual:_tableView]) {
        [_addTableView removeFromSuperview];
        if (velocity.y > 0) {
            topButton.hidden = NO;
        }
    }
}


#pragma mark - ScrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint point = scrollView.contentOffset;
    if (point.y < 0) {
        CGRect rect = header.backImgView.frame;
        rect.origin.y = point.y;
        rect.size.height = -point.y + 280;
        header.backImgView.frame = rect;
    }
}


-(void)click:(UITapGestureRecognizer *)tap{
    NSLog(@"点击图片");
    //获取点击图片的indexpath
    UIImageView *img = (UIImageView *)tap.view;
    CGPoint point = img.center;
    point = [_tableView convertPoint:point fromView:img.superview];
    _indexPath = [_tableView indexPathForRowAtPoint:point];
    
    //获取每个section的图片数量
    NSInteger imageCount = [_dataUrlArraySection[_indexPath.section] count];
    // 快速创建并进入浏览模式
    XLPhotoBrowser * browser = [XLPhotoBrowser showPhotoBrowserWithCurrentImageIndex:_indexPath.row imageCount:imageCount datasource:self];
    browser.delegate = self;
    //隐藏小圆点
    browser.showPageControl = NO;
    browser.pageControlStyle = XLPhotoBrowserPageControlStyleNone;
    // 设置长按手势弹出的地步ActionSheet数据,不实现此方法则没有长按手势
    [browser setActionSheetWithTitle:@"" delegate:self cancelButtonTitle:@"取消" deleteButtonTitle:nil otherButtonTitles:@"保存图片",@"发送给朋友",nil];
   
}



#pragma mark    -   XLPhotoBrowserDatasource
-(UIImage *)photoBrowser:(XLPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    return nil;
}


-(UIView *)photoBrowser:(XLPhotoBrowser *)browser sourceImageViewForIndex:(NSInteger)index{
    //返回指定位置
    [self returnTableViewCellWithIndex:index];
    NSInteger imageCount = 0;
    for (int i = 0; i < _indexPath.section; i++) {
        imageCount += [_dataUrlArraySection[i] count];
    }
    return _dataImageViewArray[_indexPath.section][index];
}


-(void)returnTableViewCellWithIndex:(NSInteger)index{
    NSLog(@"点击图片消失");
    NSIndexPath *selfIndexPath = [NSIndexPath indexPathForRow:index inSection:_indexPath.section];
    [_tableView scrollToRowAtIndexPath:selfIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}


-(NSURL *)photoBrowser:(XLPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
    return [NSURL URLWithString:_dataUrlArraySection[_indexPath.section][index]];
}



#pragma mark    -   XLPhotoBrowserDelegate
-(void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex{
    switch (actionSheetindex) {
        case 0:     //保存
        {
            NSLog(@"点击了actionSheet索引是：%zd，当前展示的图片索引是：%zd",actionSheetindex,currentImageIndex);
            [browser saveCurrentShowImage];
        }
            break;
        case 1:     //发送给朋友
        {
            NSLog(@"点击了actionSheet索引是：%zd，当前展示的图片索引是：%zd",actionSheetindex,currentImageIndex);
            NSLog(@"点击收藏");
            [self shareIconToWechat:currentImageIndex];
        }
            break;
        default:
        {
           NSLog(@"点击了actionSheet索引是：%zd，当前展示的图片索引是：%zd",actionSheetindex,currentImageIndex);
        }
            break;
    }
}


#pragma mark - 分享
//分享网络链接
-(void)shareWebToWechat{
    //创建分享对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //url转换成NSData(如果直接使用无法获取)
    NSString *urlString = _backImgUrl;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"小仙女推荐精品游戏:%@",_nameText] descr:@"Cx" thumImage:[UIImage imageWithData:data]];
    
    //设置网页
    shareObject.webpageUrl = [NSString stringWithFormat:@"http://chanyouji.com/trips/%@?from=groupmessage&isappinstalled=1",_selfID];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id result, NSError *error) {
        if (error) {
            NSLog(@"***********Share fail with error %@***********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}





//分享图片链接
- (void)shareIconToWechat:(NSInteger)currentImageIndex{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
      [shareObject setShareImage:[_dataImageViewArray[_indexPath.section][_indexPath.row] image]];
//    [shareObject setShareImage:[imageView image]];
    
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}


@end
